package com.fuhao.controller.portal;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.base.BaseWebController;
import com.fuhao.constants.WebConstants;
import com.fuhao.core.Constants.Constants;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.dto.input.MemberLoginInpDTO;
import com.fuhao.feign.MemberLoginServiceFeign;
import com.fuhao.feign.QQAuthoriFeign;
import com.fuhao.utils.CookieUtils;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.UserAgent;
import nl.bitwalker.useragentutils.Version;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class QQAuthoriController extends BaseWebController {
	@Autowired
	private QQAuthoriFeign qqAuthoriFeign;
	private static final String MB_QQ_QQLOGIN = "member/qqlogin";
	@Autowired
	private MemberLoginServiceFeign memberLoginServiceFeign;
	/**
	 * 重定向到首页
	 */
	private static final String REDIRECT_INDEX = "redirect:/";

	/**
	 * 生成QQ授权回调地址
	 *
	 * @return
	 */
	@RequestMapping("/qqAuth")
	public String qqAuth(HttpServletRequest request) {
		try {
			String authorizeURL = new Oauth().getAuthorizeURL(request);
			return "redirect:" + authorizeURL;
		} catch (Exception e) {
			return ERROR_500_FTL;
		}
	}

	@RequestMapping("/qqLoginBack")
	public String qqLoginBack(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
		try {
			//1.获取AccessToken
			AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
			if(accessTokenObj == null){
				return ERROR_500_FTL;
			}
			String accessToken = accessTokenObj.getAccessToken();
			if(StringUtils.isEmpty(accessToken)){
				return ERROR_500_FTL;
			}
			//2.获取OpenId
			OpenID openIDObj = new OpenID(accessToken);
			String openID = openIDObj.getUserOpenID();
			if(StringUtils.isEmpty(openID)){
				return  ERROR_500_FTL;
			}
			//封装qq登录参数
			MemberLoginInpDTO memberLoginInpDTO = new MemberLoginInpDTO();
			memberLoginInpDTO.setQqOpenId(openID);
			memberLoginInpDTO.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
			memberLoginInpDTO.setDeviceInfor(webBrowserInfo(request));
			//3.判断该OpenId是否绑定了用户
			BaseResponse<JSONObject> userInfoByOpenId = qqAuthoriFeign.findByOpenId(memberLoginInpDTO);
			if(!isSuccess(userInfoByOpenId)){
				return ERROR_500_FTL;
			}
			//3.1 若没有绑定用户,返回绑定页面进行绑定
			Integer rtnCode = userInfoByOpenId.getRtnCode();
			if(rtnCode.equals(Constants.HTTP_RES_CODE_NOTUSER_203)){
				//获取用户信息
				UserInfo userInfoObj = new UserInfo(accessToken,openID);
				if(userInfoObj == null){
					return ERROR_500_FTL;
				}
				UserInfoBean userInfo = userInfoObj.getUserInfo();
				String avatar = userInfo.getAvatar().getAvatarURL100();
				// 返回用户头像页面展示
				request.setAttribute("avatarURL100", avatar);
				httpSession.setAttribute(WebConstants.LOGIN_QQ_OPENID, openID);
				return MB_QQ_QQLOGIN;
			}
			//3.2 若该OpenId已绑定账号,返回Token
			// 自动实现登陆
			JSONObject data = userInfoByOpenId.getData();
			String token = data.getString("token");
			CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
			return REDIRECT_INDEX;
		} catch (Exception e) {
			return ERROR_500_FTL;
		}
	}

	/**
	 * 获取浏览器信息
	 *
	 * @return
	 */
	public String webBrowserInfo(HttpServletRequest request) {
		// 获取浏览器信息
		Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
		// 获取浏览器版本号
		Version version = browser.getVersion(request.getHeader("User-Agent"));
		String info = browser.getName() + "/" + version.getVersion();
		return info;
	}

}